package com.poem.controller;

import com.poem.constant.JwtClaimsConstant;
import com.poem.constant.MessageConstant;
import com.poem.dto.LoginDTO;
import com.poem.dto.RegisterDTO;
import com.poem.entity.Users;
import com.poem.properties.JwtProperties;
import com.poem.result.Result;
import com.poem.service.AuthService;
import com.poem.utils.JwtUtil;
import com.poem.vo.LoginInfo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: AuthController
 * @Author: YLY
 * @Description:
 * @Date: 2025/10/21
 * @Version: 1.0
 */
@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController {

    @Resource
    private AuthService authService;
    @Resource
    private JwtProperties jwtProperties;


    /**
     * 登录
     * @param loginDTO
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginDTO loginDTO) {
        log.info("登录:{}", loginDTO);
        LoginInfo loginInfo = authService.login(loginDTO);
        if (loginInfo.getLoginStatus() == 1){
            //登录成功生成jwt令牌
            Map<String,Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.USER_ID,loginInfo.getId());
            String token = JwtUtil
                    .createJWT(
                            jwtProperties.getSecretKey(),
                            jwtProperties.getTtl(),
                            claims);
            loginInfo.setToken(token);
            return Result.success(loginInfo);
        }else if(loginInfo.getLoginStatus() == 0){
            return Result.error(MessageConstant.USERNAME_PASSWORD_ERROR);
        }else{
            return Result.error(MessageConstant.USER_NOT_EXIST);
        }


    }

    @DeleteMapping("/logout/{username}")
    public Result logout(@PathVariable String  username){
        log.info("注销:{}", username);
        authService.deleteUser(username);
        return Result.success();
    }

    @PostMapping("/register")
    public Result register(@RequestBody RegisterDTO registerDTO){
        log.info("注册:{}", registerDTO);
        authService.addUser(registerDTO);
        return Result.success();
    }

    /**
     * 获取当前用户信息
     * @return
     */
    @GetMapping("/current")
    public Result getCurrentUser(){
        Users currentUser = authService.getCurrentUser();
        return Result.success(currentUser);
    }
}